// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const QRCode = require('../../miniprogram_npm/weapp-qrcode/index');
Page({

  
  
  data: {
    indicatorDots: true, //小点
    indicatorColor: "white", //指示点颜色
    activeColor: "white", //当前选中的指示点颜色
    autoplay: false, //是否自动轮播
    interval: 3000, //间隔时间
    duration: 2000, //滑动时间
    navtop: "",
    Batterysvalue: "0%",
    currentTimeStamp: 0,
    num: [],
    openid: "",
    name: "",
    phone: "",
    id: "",
    jhr: [],
    sfz: "",
    age: "",
    imgurl: [],
    total_walk: "xx",
    device_code: "???",
    diedao_alarm: '跌倒报警',
    sbxx: "",
    jiuzuo_alarm: {},
    jiuzuo_text:"未久坐",
    timerId: null,
    timerId1: null,
  },
  onLoad: function () {
    
    let currentTimeStamp = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0, 8)
    this.setData({
      currentTimeStamp: currentTimeStamp,
    });
    // 导航栏
    // 1.获取屏幕可使用宽度
    let windowWidth = wx.getSystemInfoSync().windowWidth;
    // 2.获取状态栏高度
    const statusBarHeight = wx.getSystemInfoSync().statusBarHeight;
    //3.获取胶囊按钮位置信息
    const menuButton = wx.getMenuButtonBoundingClientRect();
    this.setData({
      navtop: menuButton.top
    })
    

  },
  onReady() {
    this.getnew();
  },
  onShow() {
    
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 100000 // 设置较长的持续时间，以便在加载过程中持续显示
    });
    const that = this
    const app = getApp()

    app.fetchData().then(data => {
      // 数据请求成功，可以在这里进行页面加载操作
      that.setData({
        openid: app.globalData.openid
      }, function () {
        that.getdata1();
        that.getDate2(that.dingliangbaojing);

      })
    })
    that.data.timerId1 = setInterval(() => that.getdata1(), 10000);
    that.data.timerId = setInterval(() => that.getDate2(this.shenmeyebuzuo), 10000);

  },
  onHide(){
    const that =this
    setTimeout(function() {
      
      if (that.data.timerId) {
        clearInterval(that.data.timerId);
        that.data.timerId = null;
      }
      if (that.data.timerId1) {
        clearInterval(that.data.timerId1);
        that.data.timerId1 = null;
      }
      that.setData({
        total_walk: "xx",
        device_code: "???",
        diedao_alarm: '跌倒报警',
        sbxx: "",
        jiuzuo_alarm: {},
        jiuzuo_text:"未久坐",
        openid: "",
        name: "",
        phone: "",
        id: "",
        jhr: [],
        sfz: "",
        age: "",
        Batterysvalue: "0%",
        currentTimeStamp: 0,
      })
    }, 2000); // 2 秒后执行匿名函数
   
  },
  getinfo(e) {
    const itemId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../detali/detali?id=' + itemId
    })
  },
  bangding() {
    // wx.navigateTo({
    //   url: '../oldcard/oldcard',
    // })
    this.authorizationBtn()
  },
  bangding1() {
    wx.navigateTo({
      url: '../user/user',
    })
  },
  bangding11(){
        wx.navigateTo({
      url: '../oldcard/oldcard',
    })
  }
,
  getdata1() {
    const that = this
    const app = getApp()
    this.setData({
      openid: app.globalData.openid
    })
    wx.request({
      url: 'https://dj.ifankui.com/api/usr/getProfile',
      method: "POST",
      data: {
        openid: this.data.openid
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: (res) => {
        this.setData({
          name: res.data.data.lrxm,
          phone: res.data.data.lrdh,
          id: res.data.data.id,
          jhr: res.data.data.jhr,
          sfz: res.data.data.lrsfz,
        }, function () {
          let birthYear = parseInt(that.data.sfz.substring(6, 10));
          let birthMonth = parseInt(that.data.sfz.substring(10, 12));
          let birthDay = parseInt(that.data.sfz.substring(12, 14));
          // 获取当前日期
          let today = new Date();
          let currentYear = today.getFullYear();
          let currentMonth = today.getMonth() + 1;
          let currentDay = today.getDate();
          // 计算年龄
          let age = currentYear - birthYear;
          if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
            age -= +1; // 如果当前日期小于出生日期，则年龄减一
          }
          app.globalData.age = age
          this.setData({
            age: age
          })
        })
        // 提取出生年月日

      }
    })

    
  },
  getnew() {
    const that = this;
    wx.request({
      url: 'https://dj.ifankui.com/api/notice/index',
      success(res) {
        const p = res.data.notice
        for (let i = 0; i < p.length; i++) {
          p[i].dt = p[i].dt.slice(0, p[i].dt.length - 8)
        }
        that.setData({
          num: p
        })
      }
    })
    wx.request({
      url: 'https://dj.ifankui.com/api/home/index',
      success(res) {
        console.log(res);
        that.setData({
          imgurl: res.data.homeSwiper
        })
      }
    })
  },
  bddh(e) {
    console.log(e);
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone
    })
  },
  getDate2(callback) {
    const that = this
    const app = getApp()
    this.setData({
      openid: app.globalData.openid
    })
    console.log(app.globalData.openid);
    wx.request({
      url: 'https://dj.ifankui.com/api/usr/deviceList',
      method: "POST",
      data: {
        openid: this.data.openid
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: (res) => {
        console.log(res);
        if(!res.data.data[0]){
          wx.hideToast();
          return 
        }
        this.setData({
          sbxx: res.data.data[0].device_code,
        }, () => {
          that.generateQRCode(that.data.sbxx+","+that.data.sfz, 'myQrCodeCanvas');
          app.globalData.device_code=that.data.sbxx
          wx.request({
            url: 'https://dj.ifankui.com/api/device/getDeviceInfo',
            method: "POST",
            data: {
              openid: this.data.openid,
              device_code: this.data.sbxx,
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: (res) => {
              console.log(res.data.device);
              let ppp={}
              console.log(res.data.device.jiuzuo_alarm[0]);
              if(!res.data.device.jiuzuo_alarm[0]){
                  ppp=1
              }
              else {
                ppp = res.data.device.jiuzuo_alarm[0];
              }
              console.log(ppp);
              that.setData({
                Batterysvalue: res.data.device.battery,
                device_code: res.data.device.device_code,
                total_walk: res.data.device.total_walk,
                diedao_alarm: res.data.device.diedao_alarm,
                jiuzuo_alarm: ppp,
              
              }, () => {
                
                wx.hideToast();
                callback();
                const inputDate = that.data.jiuzuo_alarm.dt
                console.log(inputDate);
                function inputDate11(inputDate) {
                  if(inputDate){
                    let inputDate1 = inputDate.replace(/-/g, '/');
                    console.log(111);
                    return inputDate1
                  }
                  else {
                    let inputDate1 = ""
                    return inputDate1
                  }
                }

                let inputDate1=inputDate11(inputDate)
                if(inputDate1.length>0){                
                  const date = new Date(inputDate1);
                  // 获取当前时间
                  const now = new Date();
                  console.log(now,date);
                  // 计算时间差（单位：毫秒）
                  const diffInMillis = now - date;
                  // 将毫秒转换为分钟
                  const diffInMinutes = Math.floor(diffInMillis / (1000 * 60));
                  // 计算小时数
                  const hours = Math.floor(diffInMinutes / 60);
                  // 计算剩余分钟数
                  const minutes = diffInMinutes % 60;
                  that.setData({
                    jiuzuo_text:hours+"小时"+minutes+"分"+"前"
                  })}

                



              })
            }
          })
        })

      }

    })
    

  },

  // 授权
  authorizationBtn() {
    console.log(11);
    wx.requestSubscribeMessage({
        tmplIds: ['TY5OjBwse9wjmsgbL4dLNFrSthPIWyBFdvfFc4puwhA'],
        success(res) {
            console.log('授权成功');
            wx.showToast({
              title: '报警次数+1',
              icon: 'success'
            });
        },
        fail(err) {
            console.log('授权失败，原因：' + err.errMsg);
        }
    });
},
shenmeyebuzuo(){},
dingliangbaojing(){
  const that =this
  let percentageNumber = parseFloat(that.data.Batterysvalue.replace('%', ''));
  console.log(percentageNumber);
  if (percentageNumber < 20) {

    wx.showModal({
      title: '警告',
      content: '当前电量低于20%',
      showCancel: false, // 是否显示取消按钮
      confirmText: '确定', // 确定按钮的文字
      confirmColor: '#fb3660', // 确定按钮的文字颜色
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定');
          // 用户点击确定后的操作
        } else if (res.cancel) {
          console.log('用户点击取消');
          // 用户点击取消后的操作
        }
      }
    });

  }
},
generateQRCode(text, canvasId) {
  console.log(text);
  try {
    const qrcode = new QRCode({
      canvasId: 'myQrCanvas',
      text: text,
      width: 300,
      height: 300,
    });
    console.log('QR code generated successfully.');
  } catch (error) {
    console.error('Error generating QR code:', error);
  }
}


})